// 登录页面JavaScript逻辑
class LoginManager {
    constructor() {
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadOnlineStatus();
        this.checkExistingSession();
    }
    
    bindEvents() {
        const loginForm = document.getElementById('loginForm');
        const usernameInput = document.getElementById('username');
        const loginBtn = document.getElementById('loginBtn');
        
        // 表单提交事件
        loginForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });
        
        // 输入框事件
        usernameInput.addEventListener('input', () => {
            this.validateInput();
            this.clearError();
        });
        
        // 回车键登录
        usernameInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !loginBtn.disabled) {
                this.handleLogin();
            }
        });
        
        // 自动聚焦
        usernameInput.focus();
    }
    
    validateInput() {
        const usernameInput = document.getElementById('username');
        const loginBtn = document.getElementById('loginBtn');
        const username = usernameInput.value.trim();
        
        // 用户名验证规则
        const isValid = username.length >= 2 && 
                       username.length <= 20 && 
                       /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/.test(username);
        
        loginBtn.disabled = !isValid;
        
        // 实时验证提示
        if (username.length > 0 && !isValid) {
            if (username.length < 2) {
                this.showError('用户名至少需要2个字符');
            } else if (username.length > 20) {
                this.showError('用户名不能超过20个字符');
            } else {
                this.showError('用户名只能包含中文、英文、数字、下划线和连字符');
            }
        }
        
        return isValid;
    }
    
    async handleLogin() {
        const usernameInput = document.getElementById('username');
        const loginBtn = document.getElementById('loginBtn');
        const username = usernameInput.value.trim();
        
        if (!this.validateInput()) {
            return;
        }
        
        // 显示加载状态
        loginBtn.disabled = true;
        loginBtn.innerHTML = '<span class="loading"></span> 登录中...';
        
        try {
            // 检查服务器状态
            const serverStatus = await this.checkServerStatus();
            if (!serverStatus.available) {
                throw new Error('服务器暂时不可用，请稍后再试');
            }
            
            // 保存用户名到sessionStorage
            sessionStorage.setItem('chatUsername', username);
            sessionStorage.setItem('loginTime', new Date().toISOString());
            
            // 跳转到聊天页面
            window.location.href = '/chat';
            
        } catch (error) {
            console.error('登录失败:', error);
            this.showError(error.message || '登录失败，请重试');
            
            // 恢复按钮状态
            loginBtn.disabled = false;
            loginBtn.innerHTML = '进入聊天室';
        }
    }
    
    async checkServerStatus() {
        try {
            const response = await fetch('/api/health', {
                method: 'GET',
                timeout: 5000
            });
            
            if (response.ok) {
                const data = await response.json();
                return { available: true, data };
            } else {
                return { available: false };
            }
        } catch (error) {
            console.warn('服务器状态检查失败:', error);
            return { available: true }; // 假设可用，让WebSocket连接去处理
        }
    }
    
    async loadOnlineStatus() {
        try {
            const response = await fetch('/api/status');
            if (response.ok) {
                const data = await response.json();
                this.updateOnlineStatus(data);
            }
        } catch (error) {
            console.warn('获取在线状态失败:', error);
        }
    }
    
    updateOnlineStatus(data) {
        const onlineCountElement = document.getElementById('onlineCount');
        const serverStatusElement = document.getElementById('serverStatus');
        
        if (onlineCountElement) {
            onlineCountElement.textContent = data.onlineUsers || 0;
        }
        
        if (serverStatusElement) {
            serverStatusElement.textContent = '服务正常';
            serverStatusElement.className = 'status online';
        }
    }
    
    checkExistingSession() {
        const existingUsername = sessionStorage.getItem('chatUsername');
        if (existingUsername) {
            const usernameInput = document.getElementById('username');
            usernameInput.value = existingUsername;
            this.validateInput();
            
            // 显示提示
            this.showInfo(`欢迎回来，${existingUsername}！`);
        }
    }
    
    showError(message) {
        const errorElement = document.getElementById('errorMessage');
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            errorElement.className = 'error-message show';
        }
    }
    
    showInfo(message) {
        const errorElement = document.getElementById('errorMessage');
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            errorElement.className = 'error-message info show';
        }
    }
    
    clearError() {
        const errorElement = document.getElementById('errorMessage');
        if (errorElement) {
            errorElement.style.display = 'none';
            errorElement.className = 'error-message';
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LoginManager();
});

// 定期更新在线状态
setInterval(() => {
    const loginManager = new LoginManager();
    loginManager.loadOnlineStatus();
}, 30000); // 每30秒更新一次